package com.itheima.ydd.service.impl;

import com.itheima.ydd.dto.SysMenuDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.mapper.SysMenuMapper;
import com.itheima.ydd.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 查询所有菜单
     * @return
     */
    @Override
    public List<SysMenuDto> getAllData() {

        List<SysMenu> menuList = sysMenuMapper.selectByPid(0);
       List<SysMenuDto>sysMenuDtos= menuList.stream().map((item)->{
           SysMenuDto menuDto = new SysMenuDto();
           BeanUtils.copyProperties(item,menuDto);
           //递归查询
           this.childrenDto(menuDto);
           return menuDto;
       }).collect(Collectors.toList());
       return sysMenuDtos;
    }

    /**
     * 递归算法
     * @param menuDto
     */
    private void childrenDto(SysMenuDto menuDto) {
        Integer menuDtoId = menuDto.getId();
        List<SysMenu> sysMenus = sysMenuMapper.selectByPid(menuDtoId);
        if (sysMenus.isEmpty()){
            return;
        }
        List<SysMenuDto>sysMenuDtos=sysMenus.stream().map((menu)->{
            SysMenuDto sysMenuDto = new SysMenuDto();
            BeanUtils.copyProperties(menu,sysMenuDto);
            childrenDto(sysMenuDto);
            return sysMenuDto;
        }).collect(Collectors.toList());
        menuDto.setChildren(sysMenuDtos);

    }
}
